package com.insigma.business.qrcode.soldier.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;

import com.insigma.business.qrcode.common.util.RedisUtils;
import com.insigma.business.qrcode.soldier.entity.SoldierTpAllDO;
import com.insigma.business.qrcode.soldier.dto.SoldierBasicInfoBSearcher;
import com.insigma.business.qrcode.soldier.entity.*;
import com.insigma.business.qrcode.soldier.request.SoldierRefresherRequest;
import com.insigma.business.qrcode.soldier.service.*;
import com.insigma.business.qrcode.soldier.util.*;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;


@Component
public class SoldierExtraInfoRefresher {
    private static Logger LOGGER = LoggerFactory.getLogger(SoldierExtraInfoRefresher.class);

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private ThirdPartyService thirdPartyService;

    @Autowired
    private SoldierBasicInfoService soldierBasicInfoService;

    @Autowired
    private SoldierTpAllService soldierTpAllService;

    @Autowired
    private IrsService irsService;

    @Resource
    private ApplicationContext applicationContext;

    private String PREFIX = "SoldierExtraInfoRefresher";

    private Integer pageSize = 500;

    private Integer threadCount = 5;

    AtomicInteger atomicCount;
    private Boolean finished;

    private volatile Boolean stopFlag;

    private Boolean newFlag;

    private Boolean allTest;

    @Autowired
    private CommonDataDictService commonDataDictService;

    private String taskModule = "JOB";

    private String taskRecordKey = "ALL_INFO";

    List<String> module;



    public void refreshAllInfo(SoldierRefresherRequest request) {
        String code = request.getCode();
        Boolean newFlagParam = request.getNewFlag();

        Boolean qyFlag = request.getQyFlag();
        Boolean allTestParam = request.getAllTest();
        module = request.getModule();
        LOGGER.info("refreshAllInfo:{}", code);
        if ("STOP".equals(code)) {
            LOGGER.info("****************设置STOP****************");
            stopFlag = true;
            return;
        } else {
            stopFlag = false;
        }
        newFlag = newFlagParam;
        allTest = allTestParam;

        finished = isFinished(code);
        if (finished) {
            LOGGER.info("****************结束****************");
            return;
        }

        List<SoldierBasicInfoDO> search = getNextList(code);
        if (CollectionUtils.isEmpty(search)) {
            setFinished(code);
            LOGGER.info("****************结束****************");
            return;
        }
        commonDataDictService.append(taskModule, taskRecordKey, "任务开始:" + DateUtil.formatDate(new Date(), "yyyy:MM:dd HH:mm:ss"));
        ConcurrentLinkedQueue<SoldierBasicInfoDO> queue = new ConcurrentLinkedQueue<SoldierBasicInfoDO>(search);

        for (int i = 0; i < threadCount; i++) {
            ThreadPoolManager.getInstance().submit(
                    new Runnable() {
                        @Override
                        public void run() {
                            while (!finished) {

                                while (!queue.isEmpty()) {

                                    if (stopFlag) {
                                        LOGGER.info("****************************程序主动退出***********************");
                                        return;
                                    }

                                    SoldierBasicInfoDO soldierBasicInfoDO = queue.poll();
                                    LOGGER.info("**********************loooooooooooooop:{},   idCardNo: {}", atomicCount.incrementAndGet(), soldierBasicInfoDO.getIdCardNo());
                                    SoldierTpAllDO soldierTpAllDO = soldierTpAllService.getByIdCardNo(soldierBasicInfoDO.getIdCardNo());
                                    boolean newAddFlag = false;
                                    if (soldierTpAllDO == null) {
                                        newAddFlag = true;
                                        soldierTpAllDO = new SoldierTpAllDO();
                                        soldierTpAllDO.setIdCardNo(soldierBasicInfoDO.getIdCardNo());
                                        soldierTpAllDO.setNickName(soldierBasicInfoDO.getRealName());
                                        soldierTpAllService.insert(soldierTpAllDO);
                                    }
                                    try {
                                        if (Boolean.TRUE.equals(qyFlag)) {
                                            queryQyInfo(soldierTpAllDO, soldierBasicInfoDO.getIdCardNo(), soldierBasicInfoDO.getRealName(), soldierBasicInfoDO.getGender());
                                        } else {
                                            queryAndInsertExtraInfo(soldierTpAllDO, soldierBasicInfoDO.getIdCardNo(), soldierBasicInfoDO.getRealName(), soldierBasicInfoDO.getGender(), newAddFlag);
                                        }
                                    } catch (Exception e) {
                                        TroubleshootLogsUtils.LOGGER.error("执行出错:{}", e);
                                    }
                                }
                                List<SoldierBasicInfoDO> nextList = getNextList(code);
                                if (CollectionUtils.isEmpty(nextList) && queue.isEmpty()) {
                                    setFinished(code);
                                    finished = true;
                                    commonDataDictService.append(taskModule, taskRecordKey, "任务结束:" + DateUtil.formatDate(new Date(), "yyyy:MM:dd HH:mm:ss"));
                                    LOGGER.info("同步数据结束：****************结束****************");
                                    return;
                                }
                                queue.addAll(nextList);
                            }
                        }
                    }
            );
        }
    }


    public SoldierTpAllDO refreshByIdCardNoNotCheck(String idCardNo, String name) {
        SoldierTpAllDO soldierTpAllDO = soldierTpAllService.getByIdCardNo(idCardNo);
        if (soldierTpAllDO == null) {
            soldierTpAllDO = new SoldierTpAllDO();
            soldierTpAllDO.setIdCardNo(idCardNo);
            soldierTpAllDO.setNickName(name);
            soldierTpAllService.insert(soldierTpAllDO);
        }
        queryAndInsertExtraInfo(soldierTpAllDO, idCardNo, name, "MALE", true);
        return soldierTpAllDO;
    }

    public SoldierTpAllDO refreshByIdCardNo(String idCardNo) {
        SoldierTpAllDO soldierTpAllDO = soldierTpAllService.getByIdCardNo(idCardNo);
        SoldierBasicInfoDO soldierBasicInfoDO = soldierBasicInfoService.getByIdCardNo(idCardNo);
        if (soldierTpAllDO == null) {
            soldierTpAllDO = new SoldierTpAllDO();
            soldierTpAllDO.setIdCardNo(idCardNo);
            soldierTpAllDO.setNickName(soldierBasicInfoDO.getRealName());
            soldierTpAllService.insert(soldierTpAllDO);
        }
        queryAndInsertExtraInfo(soldierTpAllDO, soldierBasicInfoDO.getIdCardNo(), soldierBasicInfoDO.getRealName(), soldierBasicInfoDO.getGender(), true);
        return soldierTpAllDO;
    }

    private void queryQyInfo(SoldierTpAllDO soldierTpAllDO, String idCardNo, String name, String gender) {
        boolean changed = false;
        if (soldierTpAllDO.isSocialSecurityFlag()) {
            String socialSecurity = soldierTpAllDO.getSocialSecurity();
            List<InsuredInfoEntity> insuredInfoEntities = JSONArray.parseArray(socialSecurity, InsuredInfoEntity.class);
            Collections.sort(insuredInfoEntities, new Comparator<InsuredInfoEntity>() {
                @Override
                public int compare(InsuredInfoEntity o1, InsuredInfoEntity o2) {
                    return o2.getSjsbsj().compareTo(o1.getSjsbsj());
                }
            });
            InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
            String companyName = lastOne.getAab004();
            List<TaxEnterpriseInfoEntity> taxEnterpriseInfoEntities = thirdPartyService.queryTaxEnterpriseList(null, companyName);
            if (!CollectionUtils.isEmpty(taxEnterpriseInfoEntities)) {
                soldierTpAllDO.setJobTaxCompanyFlag(true);
                soldierTpAllDO.setJobTaxCompany(JSON.toJSONString(taxEnterpriseInfoEntities));
            }
            changed = true;
        }

        if (soldierTpAllDO.isShareholderFlag()) {
            String shareholder = soldierTpAllDO.getShareholder();
            List<ShareholderEntity> shareholderEntities = JSONArray.parseArray(shareholder, ShareholderEntity.class);
            ShareholderEntity shareholderEntity = shareholderEntities.get(0);
            List<TaxEnterpriseInfoEntity> taxEnterpriseInfoEntities = thirdPartyService.queryTaxEnterpriseList(shareholderEntity.getUniscid(), null);
            if (!CollectionUtils.isEmpty(taxEnterpriseInfoEntities)) {
                soldierTpAllDO.setShareTaxCompanyFlag(true);
                soldierTpAllDO.setShareTaxCompany(JSON.toJSONString(taxEnterpriseInfoEntities));
            }
            changed = true;
        }
        if (changed) {
            soldierTpAllService.update(soldierTpAllDO);
        }
    }


    private void queryAndInsertExtraInfo(SoldierTpAllDO soldierTpAllDO, String idCardNo, String name, String gender, boolean newAddFlag) {
        if (Strings.isBlank(gender)) {
            gender = "M";
        }

        if (checkIsNeed("inusreList", newAddFlag)) {
            List<InsuredInfoEntity> insuredInfoEntities = thirdPartyService.queryInusreList(idCardNo, name);
            if (!CollectionUtils.isEmpty(insuredInfoEntities)) {
                Collections.sort(insuredInfoEntities, new Comparator<InsuredInfoEntity>() {
                    @Override
                    public int compare(InsuredInfoEntity o1, InsuredInfoEntity o2) {
                        return o2.getSjsbsj().compareTo(o1.getSjsbsj());
                    }
                });
                if (!CollectionUtils.isEmpty(insuredInfoEntities)) {

                    checkIsSocialSecurityChange(soldierTpAllDO, insuredInfoEntities);

                    checkIsWithdraw(soldierTpAllDO.getIdCardNo(), soldierTpAllDO.getNickName(), insuredInfoEntities);

                    soldierTpAllDO.setSocialSecurityFlag(true);
                    soldierTpAllDO.setSocialSecurity(JSON.toJSONString(insuredInfoEntities));

                    InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
                    String aae036 = lastOne.getAae036();
                    soldierTpAllDO.setLatestSocialTime(aae036);

                    String companyName = lastOne.getAab004();
                    try {
                        List<TaxEnterpriseInfoEntity> taxEnterpriseInfoEntities = thirdPartyService.queryTaxEnterpriseList(null, companyName);
                        if (!CollectionUtils.isEmpty(taxEnterpriseInfoEntities)) {
                            soldierTpAllDO.setJobTaxCompanyFlag(true);
                            soldierTpAllDO.setJobTaxCompany(JSON.toJSONString(taxEnterpriseInfoEntities));
                        }
                    } catch (MaxCountException e) {
                        TroubleshootLogsUtils.LOGGER.error("MaxCountException:{}", e);

                    }
                }
            }
        }

        if (checkIsNeed("providentFund", newAddFlag)) {
            List<ProvidentFundEntity> providentFundEntities = thirdPartyService.queryProvidentFund(idCardNo, name);
            if (!CollectionUtils.isEmpty(providentFundEntities)) {
                soldierTpAllDO.setProvidentFundFlag(true);
                soldierTpAllDO.setProvidentFund(JSON.toJSONString(providentFundEntities));
            }
        }













        if (checkIsNeed("subsistenceAllowance", newAddFlag)) {
            try {
                List<IrsSubsistenceEntity> subsistenceAllowanceEntities = irsService.queryDibao(idCardNo);
                if (!CollectionUtils.isEmpty(subsistenceAllowanceEntities)) {
                    soldierTpAllDO.setSubsistenceAllowanceFlag(true);
                    soldierTpAllDO.setSubsistenceAllowance(JSON.toJSONString(subsistenceAllowanceEntities));
                } else if (subsistenceAllowanceEntities != null) {
                    soldierTpAllDO.setSubsistenceAllowanceFlag(false);
                    soldierTpAllDO.setSubsistenceAllowance(null);
                }
            } catch (MaxCountException e) {
                TroubleshootLogsUtils.LOGGER.error("MaxCountException:{}", e);

            }
        }

        if (checkIsNeed("lowSide", newAddFlag)) {
            try {
                List<IrsLowSideEntity> lowSideEntities = irsService.queryDibian(idCardNo, name);
                if (!CollectionUtils.isEmpty(lowSideEntities)) {
                    soldierTpAllDO.setLowSideFlag(true);
                    soldierTpAllDO.setLowSide(JSON.toJSONString(lowSideEntities));
                } else if (lowSideEntities != null) {
                    soldierTpAllDO.setLowSideFlag(false);
                    soldierTpAllDO.setLowSide(null);
                }
            } catch (MaxCountException e) {
                TroubleshootLogsUtils.LOGGER.error("MaxCountException:{}", e);

            }
        }

        if (checkIsNeed("extremelyPoor", newAddFlag)) {
            try {
                List<IrsExtremelyPoorEntity> irsExtremelyPoorEntities = irsService.queryTekun(idCardNo, name);
                if (!CollectionUtils.isEmpty(irsExtremelyPoorEntities)) {
                    soldierTpAllDO.setExtremelyPoorFlag(true);
                    soldierTpAllDO.setExtremelyPoor(JSON.toJSONString(irsExtremelyPoorEntities));
                } else if (irsExtremelyPoorEntities != null) {
                    soldierTpAllDO.setExtremelyPoorFlag(false);
                    soldierTpAllDO.setExtremelyPoor(null);
                }
            } catch (MaxCountException e) {
                TroubleshootLogsUtils.LOGGER.error("MaxCountException:{}", e);

            }
        }

        if (checkIsNeed("unemploymentRegistration", newAddFlag)) {
            List<UnemploymentRegistrationEntity> unemploymentRegistrationEntities = thirdPartyService.queryUnemploymentRegistration(idCardNo, name);
            if (!CollectionUtils.isEmpty(unemploymentRegistrationEntities)) {
                soldierTpAllDO.setUnemploymentRegistrationFlag(true);
                soldierTpAllDO.setUnemploymentRegistration(JSON.toJSONString(unemploymentRegistrationEntities));
                Collections.sort(unemploymentRegistrationEntities, new Comparator<UnemploymentRegistrationEntity>() {
                    @Override
                    public int compare(UnemploymentRegistrationEntity o1, UnemploymentRegistrationEntity o2) {
                        return o2.getAae044().compareTo(o1.getAae044());
                    }
                });
                String aae044 = unemploymentRegistrationEntities.get(0).getAae044();
                soldierTpAllDO.setUnemploymentRegistrationTime(aae044);

                checkIsNeedToRegistration(unemploymentRegistrationEntities);
            }
        }

        if (checkIsNeed("medicalInsuranceConsume", newAddFlag)) {
            try {
                MedicalInsuranceConsumptionEntity medicalInsuranceConsumptionEntity = thirdPartyService.queryMedicalInsuranceConsume(idCardNo, name);





                if (medicalInsuranceConsumptionEntity != null) {
                    medicalInsuranceConsumptionEntity.setStartTime(LocalDateTime.now());
                    soldierTpAllDO.setMedicalInsuranceConsumptionFlag(true);

                    Set<MedicalInsuranceConsumptionEntity> set = Sets.newHashSet(medicalInsuranceConsumptionEntity);
                    if (Strings.isNotBlank(soldierTpAllDO.getMedicalInsuranceConsumption())) {
                        Object parse = JSON.parse(soldierTpAllDO.getMedicalInsuranceConsumption());
                        if (parse != null) {
                            if (parse instanceof JSONObject) {
                                JSONObject jsonObject = (JSONObject) parse;
                                MedicalInsuranceConsumptionEntity oldEntity = jsonObject.toJavaObject(MedicalInsuranceConsumptionEntity.class);
                                set.add(oldEntity);
                            }
                            if (parse instanceof JSONArray) {
                                JSONArray jsonArray = (JSONArray) parse;
                                List<MedicalInsuranceConsumptionEntity> medicalInsuranceConsumptionEntities = jsonArray.toJavaList(MedicalInsuranceConsumptionEntity.class);
                                set.addAll(medicalInsuranceConsumptionEntities);
                            }
                        }
                    }
                    soldierTpAllDO.setMedicalInsuranceConsumption(JSONArray.toJSONString(set));
                }
            } catch (Exception e) {
                TroubleshootLogsUtils.LOGGER.error("请求医疗消费错误:{}", e);
            }
        }

        if (checkIsNeed("disabledInfo", newAddFlag)) {
            DisabledEntity disabledEntity = thirdPartyService.queryDisabledInfo(idCardNo);
            if (disabledEntity != null) {
                soldierTpAllDO.setDisabledConsumptionFlag(true);
                soldierTpAllDO.setDisabled(JSON.toJSONString(disabledEntity));
            }
        }

        if (checkIsNeed("newHouseholdRegistrationInfo", newAddFlag)) {
            List<SoldierNewHouseholdRegistrationInfoDO> householdRegistrationInfoDOS = thirdPartyService.queryNewHouseholdRegistrationInfo(idCardNo, name);
            if (!CollectionUtils.isEmpty(householdRegistrationInfoDOS)) {


                soldierTpAllDO.setNewHouseholdRegistrationFlag(true);
                soldierTpAllDO.setNewHouseholdRegistration(JSON.toJSONString(householdRegistrationInfoDOS));
            }
        }










        if (checkIsNeed("floatingPopulationList", newAddFlag)) {
            List<FloatingPopulationEntity> floatingPopulationEntities = irsService.queryFloatingPopulationList(idCardNo, name);
            if (!CollectionUtils.isEmpty(floatingPopulationEntities)) {
                soldierTpAllDO.setFloatingPopulationFlag(true);
                soldierTpAllDO.setFloatingPopulation(JSON.toJSONString(floatingPopulationEntities));
            }
        }

        if (checkIsNeed("houseList", newAddFlag)) {
            List<HouseEntity> houseEntities = thirdPartyService.queryHouseList(idCardNo, name);
            if (!CollectionUtils.isEmpty(houseEntities)) {
                soldierTpAllDO.setHouseFlag(true);
                soldierTpAllDO.setHouse(JSON.toJSONString(houseEntities));
            }
        }

        if (checkIsNeed("carList", newAddFlag)) {
            List<CarEntity> carEntities = thirdPartyService.queryCarList(idCardNo);
            if (!CollectionUtils.isEmpty(carEntities)) {
                soldierTpAllDO.setCarFlag(true);
                soldierTpAllDO.setCar(JSON.toJSONString(carEntities));
            }
        }

        if (checkIsNeed("untrustworthy", newAddFlag)) {
            List<UntrustworthyEntity> untrustworthyEntities = irsService.queryUntrustworthy(idCardNo, name);
            if (!CollectionUtils.isEmpty(untrustworthyEntities)) {
                soldierTpAllDO.setUntrustworthyFlag(true);
                soldierTpAllDO.setUntrustworthy(JSON.toJSONString(untrustworthyEntities));
            }
        }

        if (checkIsNeed("communityCorrectionList", newAddFlag)) {
            List<CommunityCorrectionEntity> communityCorrectionEntities = irsService.queryCommunityCorrectionList(idCardNo);
            if (!CollectionUtils.isEmpty(communityCorrectionEntities)) {
                soldierTpAllDO.setCommunityCorrectionFlag(true);
                soldierTpAllDO.setCommunityCorrection(JSON.toJSONString(communityCorrectionEntities));
            }
        }

        if (checkIsNeed("effectiveJudgmentList", newAddFlag)) {
            List<EffectiveJudgmentEntity> effectiveJudgmentEntities = thirdPartyService.queryEffectiveJudgmentList(idCardNo, name);
            if (!CollectionUtils.isEmpty(effectiveJudgmentEntities)) {
                soldierTpAllDO.setEffectiveJudgmentFlag(true);
                soldierTpAllDO.setEffectiveJudgment(JSON.toJSONString(effectiveJudgmentEntities));
            }
        }

        if (checkIsNeed("shareholderList", newAddFlag)) {
            List<ShareholderEntity> shareholderEntities = irsService.queryShareholderList(idCardNo);
            if (!CollectionUtils.isEmpty(shareholderEntities)) {
                soldierTpAllDO.setShareholderFlag(true);
                soldierTpAllDO.setShareholder(JSON.toJSONString(shareholderEntities));

                List<EnterpriseInfoEntity> enterpriseInfoEntities = new ArrayList<>();
                for (ShareholderEntity shareholderEntity : shareholderEntities) {
                    enterpriseInfoEntities = irsService.queryEnterpriseList(shareholderEntity.getUniscid());
                }
                soldierTpAllDO.setCompanyFlag(true);
                soldierTpAllDO.setCompany(JSON.toJSONString(enterpriseInfoEntities));


                ShareholderEntity shareholderEntity = shareholderEntities.get(0);
                try {
                    List<TaxEnterpriseInfoEntity> taxEnterpriseInfoEntities = thirdPartyService.queryTaxEnterpriseList(shareholderEntity.getUniscid(), null);
                    if (!CollectionUtils.isEmpty(taxEnterpriseInfoEntities)) {
                        soldierTpAllDO.setShareTaxCompanyFlag(true);
                        soldierTpAllDO.setShareTaxCompany(JSON.toJSONString(taxEnterpriseInfoEntities));
                    }
                } catch (MaxCountException e) {
                    TroubleshootLogsUtils.LOGGER.error("{}", e);
                    soldierTpAllDO.setShareTaxCompany("");
                }
            }
        }

        if (checkIsNeed("deadInfo", newAddFlag) && !Boolean.TRUE.equals(soldierTpAllDO.isDeadInfoFlag())) {
            List<DeadInfoIrsEntity> deadInfoIrsEntities = irsService.queryDeadCremateInfo(idCardNo);
            if (!CollectionUtils.isEmpty(deadInfoIrsEntities)) {
                soldierTpAllDO.setDeadInfoFlag(true);
                soldierTpAllDO.setDeadInfo(JSON.toJSONString(deadInfoIrsEntities));
                soldierTpAllDO.setDeadTime(deadInfoIrsEntities.get(0).getDurdeathdate());

                applicationContext.publishEvent(new SoldierDeadEvent(idCardNo, deadInfoIrsEntities.get(0).getDurdeathdate(), deadInfoIrsEntities.get(0).getDURPVDNO()));
            }
        }

        soldierTpAllService.update(soldierTpAllDO);
    }

    private void checkIsNeedToRegistration(List<UnemploymentRegistrationEntity> unemploymentRegistrationEntities) {
        Collections.sort(unemploymentRegistrationEntities, new Comparator<UnemploymentRegistrationEntity>() {
            @Override
            public int compare(UnemploymentRegistrationEntity o1, UnemploymentRegistrationEntity o2) {
                return o2.getAae044().compareTo(o1.getAae044());
            }
        });

        UnemploymentRegistrationEntity unemploymentRegistrationEntity = unemploymentRegistrationEntities.get(0);
        Date date = org.apache.commons.lang3.time.DateUtils.addMonths(new Date(), -12);
        String unemploymentRegistrationTime = DateUtil.formatDate(date, "yyyy-MM");

        if (unemploymentRegistrationEntity.getAae044().compareTo(unemploymentRegistrationTime) > 0 &&
                "有效".equals(unemploymentRegistrationEntity.getAae100())) {
            applicationContext.publishEvent(new UnemploymentRegistrationEvent(unemploymentRegistrationEntity.getAac002(), unemploymentRegistrationEntity.getAac003(), unemploymentRegistrationEntity.getAae044()));
        }
    }

    private void checkIsWithdraw(String idCardNo, String name, List<InsuredInfoEntity> insuredInfoEntities) {
        String socialUnemploymentTime = DateUtil.formatDate(org.apache.commons.lang3.time.DateUtils.addMonths(new Date(), -4), "yyyy-MM-dd");
        Collections.sort(insuredInfoEntities, new Comparator<InsuredInfoEntity>() {
            @Override
            public int compare(InsuredInfoEntity o1, InsuredInfoEntity o2) {
                return o2.getAae036().compareTo(o1.getAae036());
            }
        });
        InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
        String lastTime = lastOne.getAae036();
        if (lastTime.compareTo(socialUnemploymentTime) < 0) {

            applicationContext.publishEvent(new SocialSecurityWithdrawEvent(idCardNo, name, lastTime));
        }
    }


    private void checkIsSocialSecurityChange(SoldierTpAllDO soldierTpAllDO, List<InsuredInfoEntity> insuredInfoEntities) {
        String socialSecurity = soldierTpAllDO.getSocialSecurity();
        if (Strings.isBlank(socialSecurity)) {
            return;
        }
        List<InsuredInfoEntity> oldOnes = JSONArray.parseArray(socialSecurity, InsuredInfoEntity.class);

        Collections.sort(oldOnes, new Comparator<InsuredInfoEntity>() {
            @Override
            public int compare(InsuredInfoEntity o1, InsuredInfoEntity o2) {
                return o2.getSjsbsj().compareTo(o1.getSjsbsj());
            }
        });
        InsuredInfoEntity oldLast = oldOnes.get(0);
        String companyName = oldLast.getAab004();

        InsuredInfoEntity newOne = insuredInfoEntities.get(0);
        String newCompanyName = newOne.getAab004();
        if (!companyName.equals(newCompanyName)) {
            applicationContext.publishEvent(new SocialSecurityEvent(soldierTpAllDO.getIdCardNo(), companyName, newCompanyName));
        }
    }


    private void checkIsHouseHoldChange(SoldierTpAllDO soldierTpAllDO, SoldierHouseholdRegistrationInfoDO registrationInfoDO) {
        String householdRegistration = soldierTpAllDO.getHouseholdRegistration();
        if (Strings.isBlank(householdRegistration)) {
            return;
        }

        SoldierHouseholdRegistrationInfoDO houseInfo = JSONObject.parseObject(householdRegistration, SoldierHouseholdRegistrationInfoDO.class);
        String orgin = houseInfo.getHjdz();
        String hjdz = registrationInfoDO.getHjdz();
        if (!orgin.equals(hjdz)) {
            applicationContext.publishEvent(new RootAdminAreaChangeEvent(soldierTpAllDO.getIdCardNo(), orgin, hjdz));
        }
    }

    private boolean checkIsNeed(String name, boolean newAddFlag) {
        if (newAddFlag) {
            return true;
        }
        if (CollectionUtils.isEmpty(module) || module.contains(name)) {
            LOGGER.info("刷新模块：{}", name);
            return true;
        }

        return false;
    }

    private String idCardNoToBirthday(String idCardNo) {
        if (Strings.isBlank(idCardNo) || idCardNo.length() < 15) {
            return "";
        }
        String y = idCardNo.substring(6, 10);
        String m = idCardNo.substring(10, 12);
        String d = idCardNo.substring(12, 14);
        return y + "-" + m + "-" + d;
    }

    private List<SoldierBasicInfoDO> getNextList(String code) {
        String lock = "GET-NEXT-LIST-LOCK";
        boolean b = redisLock.tryLock(lock, 1000 * 60);
        if (!b) {
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                TroubleshootLogsUtils.LOGGER.error("任务错误:{}", e);
                e.printStackTrace();
            }
            return new ArrayList<>();
        }
        Integer pageNo = getNextPage(code);
        atomicCount = new AtomicInteger(pageSize * (pageNo - 1));
        LOGGER.info("开始刷新,  pageNo:{}", pageNo);
        SoldierBasicInfoBSearcher innerSearcher = new SoldierBasicInfoBSearcher(pageNo, pageSize);
        innerSearcher.setSortKeyValueJoint("id_asc");
        List<SoldierBasicInfoDO> search;
        if (Boolean.TRUE.equals(newFlag)) {
            search = soldierBasicInfoService.searchNewNotInTpAll(innerSearcher);
        } else if (Boolean.TRUE.equals(allTest)) {
            search = soldierTpAllService.searchAll();
        } else {
            search = soldierBasicInfoService.search(innerSearcher);
        }
        redisLock.unlock(lock);
        return search;
    }

    private boolean isFinished(String code) {
        String key = PREFIX + "_" + code + "_finished";
        Object o = redisUtils.get(key);
        if (o == null) {
            return false;
        }
        return true;
    }

    private void setFinished(String code) {
        String key = PREFIX + "_" + code + "_finished";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm");
        Date now = new Date();
        String nowTime = sdf.format(now);
        LOGGER.info("{}, finished at {}", code, nowTime);
        redisUtils.set(key, nowTime);
    }

    private Integer getNextPage(String code) {
        String key = PREFIX + "_" + code + "_current_page";
        Object o = redisUtils.get(key);
        if (o == null) {
            redisUtils.set(key, 1);
            return 1;
        }
        Integer i = (Integer) o;
        redisUtils.set(key, i + 1);
        return i + 1;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
        ScheduledFuture future1 = null;
        ScheduledFuture finalFuture = future1;
        Runnable task1 = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 6; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Taskrepeating.");
                }
                finalFuture.cancel(true);


            }
        };
        future1 = service.scheduleAtFixedRate(task1, 0, 1, TimeUnit.SECONDS);
    }

}
